<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { Breadcrumb, BreadcrumbItem, Button, Dropdown, Input, Menu, Pagination } from 'ant-design-vue';
import { fetchAllCompetitionsApi } from '@/api/innovationSquare/competitionApi';
import CompetitionMarket from './CompetitionMarket.vue'
import type { Competition } from '../types/Competition';
import { DownOutlined } from '@ant-design/icons-vue';
import NormalHeader from '@/components/NormalHeader.vue';

import router from '@/router';
const categories = ref([
  '全部', '本科生竞赛', '研究生竞赛', '国家级比赛', '校内选拔赛',
  '创新比赛', '创业比赛', '学科竞赛', '计算机学院（国家示范性软件学院）', '信息与通信学院',
  '人工智能学院', '人文学院', '集成电路学院', '智能工程与自动化学院', '国际学院',
  '经济管理学院', '理学院', '校团委', '叶培大创新创业学院', '研究生院',
]);

const selectedCategory = ref(categories.value[0]);
const competitions = ref<Competition[]>([]);
const sortOrder = ref('publisher_time');
const searchTerm = ref<String>('');
const loading = ref(false);
const currentPage = ref(1);
// const defaultUserId = 1; // 默认的 userId
const totalCompetitions = ref<number>(); // 假设总页数为150
const totalPages = ref<number>(); // 假设总页数为15
const titleParts = '双创广场 > 赛事信息'.split(' > ');

const fetchCompetitions = async (reset = false) => {
  loading.value = true;
  try {
    const params: any = {
      pageNum: String(currentPage.value),
      sentence: searchTerm.value || "",
      tags: selectedCategory.value === '全部' ? [] : [selectedCategory.value],
      sortBy: sortOrder.value,
      // userId: defaultUserId,
    };

    const res = await fetchAllCompetitionsApi(params)
    if (res) {
      competitions.value = reset ? res.records : [...res.records];
      totalPages.value = res.pages || 15;
      totalCompetitions.value = res.total || 150;
    }
  }
  catch (error) {
    console.error('Error fetching competitions:', error);
  }
  finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchCompetitions(true);
});

const handleCategoryClick = (category: string) => {
  selectedCategory.value = category;
  currentPage.value = 1;
  fetchCompetitions(true);
};

const handleSortChange = (value: any) => {
  sortOrder.value = value.key.toString();
  currentPage.value = 1;
  fetchCompetitions(true)
};

const handleSearch = (value: string) => {
  searchTerm.value = value;
  // console.log('搜索', searchTerm);
  currentPage.value = 1;
  fetchCompetitions(true);
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchCompetitions(true);
};

const menuItems = computed(() =>
  categories.value.slice(8).map((category, index) => ({
    key: `more-${index}`,
    label: category,
  })),
);

const handleBreadcrumbClick = (part: string) => {
  if (part === '双创广场')
    router.push('/user/dachuang');
}
</script>

<template>
  <a-layout>
    <NormalHeader title="赛事信息" />
    <div style="margin: 1rem; margin-top: 0%; margin-bottom: 0%;background-color: transparent; display: flex; flex-direction: column; border-radius: 0.5rem; max-height: 80vh;">
      <div style="display: flex; flex-direction: row; justify-content: space-between;">
        <Breadcrumb separator=">" :style="{ fontSize: '1.5rem', fontWeight: 'bold' }">
          <BreadcrumbItem
            v-for="(part, index) in titleParts.slice(0, -1)"
            :key="index"
            style="color: #A0A0A0; cursor: pointer;"
            @click="handleBreadcrumbClick(part)"
          >
            {{ part }}
          </BreadcrumbItem>
          <BreadcrumbItem>{{ titleParts[titleParts.length - 1] }}</BreadcrumbItem>
        </Breadcrumb>
      </div>

      <a-flex style="padding-left: 0rem; padding-right: 0rem;">
        <Input.Search
          v-model="searchTerm"
          placeholder="搜索竞赛"
          style="min-width: 20vh; padding-right: 0.2rem;"
          @search="handleSearch"
        />

        <Dropdown :trigger="['click']">
          <template #overlay>
            <Menu @click="handleSortChange">
              <Menu.Item key="publisher_time">
                最新
              </Menu.Item>
              <Menu.Item key="look_num">
                最多浏览
              </Menu.Item>
              <Menu.Item key="like_num">
                最多收藏
              </Menu.Item>
              <Menu.Item key="share_num">
                最多转发
              </Menu.Item>
            </Menu>
          </template>

          <Button style="background-color: transparent; margin-right: 2rem;">
            排序：{{ sortOrder === 'publisher_time' ? '最新' : '最多收藏' }} <DownOutlined />
          </Button>
        </Dropdown>
      </a-flex>

      <a-flex wrap="wrap" style="max-width: 80vw;">
        <a-Button
          v-for="(category, index) in categories.slice(0, 8)"
          :key="index"
          :type="selectedCategory === category ? 'primary' : 'default'"
          style="margin-top: 0.2rem; font-size: 0.8rem; margin-right: 0.2rem; font-weight: bold;"
          @click="() => handleCategoryClick(category)"
        >
          {{ category }}
        </a-Button>

        <a-dropdown trigger="['click']">
          <a style="margin-top: 0.7rem; margin-left: 1rem;" @click.prevent>
            更多
            <DownOutlined />
          </a>

          <template #overlay>
            <a-menu>
              <a-menu-item v-for="item in menuItems" :key="item.key">
                <a @click.prevent="handleCategoryClick(item.label)">{{ item.label }}</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </a-flex>

      <a-layout-content style="background-color: transparent; margin-top: 1rem;">
        <div v-if="competitions.length > 0" style="max-height: 100%; max-width: 100%; overflow: auto;">
          <CompetitionMarket :competitions="competitions" />
        </div>
        <div v-else>
          <p>暂无数据</p>
        </div>
      </a-layout-content>
    </div>

    <a-layout-footer style="background-color: transparent;">
      <div style="text-align: center;">
        <Pagination
          v-model:current="currentPage"
          :total="totalCompetitions"
          :page-size="10"
          show-quick-jumper
          :show-total="(total: number) => `总共 ${total} 项`"
          class="pagination"
          @change="handlePageChange"
        />
      </div>
    </a-layout-footer>
  </a-layout>
</template>

<style scoped lang="scss">
</style>
